package au.edu.unsw.editingtool.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;

import org.xml.sax.SAXException;

import au.edu.unsw.editingtool.db.DBClaim;
import au.edu.unsw.editingtool.fedora.FedoraFactory;
import au.edu.unsw.editingtool.global.EditingToolException;
import au.edu.unsw.editingtool.global.GlobalConstant;
import au.edu.unsw.editingtool.global.Metadata;
import au.edu.unsw.editingtool.global.PropertyReader;
import au.edu.unsw.editingtool.global.Util;

/**
 * Servlet implementation class ClaimR
 */
public class Claim extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String ServletContext = null;
	private String ApplicationContext = null;
	private String ApplicationPath = null;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Claim() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doService(request, response);
	}
	
	protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext = getServletContext().getRealPath("") + GlobalConstant.fileSeparator;
		ApplicationContext = request.getLocalName()+":"+request.getServerPort()+"/"+
							GlobalConstant.APPLICATIONNAME+"/";
		ApplicationPath = request.getContextPath();
		System.out.println("==== [CLAIM Servlet] ====");
		
		HttpSession session = request.getSession(false);
		Hashtable <String,String> tb = (Hashtable<String, String>) session.getAttribute(GlobalConstant.requestFormData);
		String ctrlLast = (String) session.getAttribute(GlobalConstant.requestLastCommand);	
		System.out.println("[CLAIM] requestLastCommand = "+ctrlLast);
		
		String pid = null;
		pid = (String) request.getAttribute(GlobalConstant.pid);
		if (pid ==null)
			pid = request.getParameter(GlobalConstant.pid);
		
		String ctrl = null; 		
		if(request.getParameter(GlobalConstant.requestCommand)!=null)
		{
				ctrl = request.getParameter(GlobalConstant.requestCommand);
				System.out.println("[CLAIM] Param requestCommand = "+ctrl);
		}
		
		if(request.getAttribute(GlobalConstant.requestCommand)!=null)
		{
			ctrl = (String) request.getAttribute(GlobalConstant.requestCommand);
			System.out.println("[CLAIM] Attr requestCommand = "+ctrl);
		}
		
		if(ctrl==null)
			ctrl="";
		
		if(tb!=null && (ctrl.compareTo(GlobalConstant.cmdClaimPreview)==0))
		{
			//Update Hashtable from the parameter in the form.			
			Enumeration keys = request.getParameterNames();
			while(keys.hasMoreElements())
			{
				String key = (String) keys.nextElement();
				tb.put(key, request.getParameter(key));			
			}	
			//DEBUG 			 
			//for(Enumeration sesskeys = session.getAttributeNames();sesskeys.hasMoreElements();)
			//{
			//	String sesskey = (String) sesskeys.nextElement();
			//	System.out.println("Preview - Key : "+sesskey+" and Value : "+session.getAttribute(sesskey.toString()));
			//}
			session.setAttribute(GlobalConstant.requestFormData,tb);					
			session.setAttribute(GlobalConstant.requestLastCommand,GlobalConstant.cmdClaimPreview);
			request.setAttribute(GlobalConstant.pid,pid);
			
			System.out.println("[CLAIM] Forward to "+GlobalConstant.JSPClaimPreview);
			RequestDispatcher rd = request.getRequestDispatcher(GlobalConstant.JSPClaimPreview);
			rd.forward(request, response);
			return;
		}
		else if(ctrl.compareTo(GlobalConstant.cmdClaim)==0)
		{
			//TODO
			// Proper login for claim page
			session.removeAttribute(GlobalConstant.requestFormData);					
			session.setAttribute(GlobalConstant.requestLastCommand,GlobalConstant.cmdClaim);
			request.setAttribute(GlobalConstant.pid,pid);
			
			System.out.println("[CLAIM] forward to "+GlobalConstant.JSPClaim);
			RequestDispatcher rd = request.getRequestDispatcher(GlobalConstant.JSPClaim);
			rd.forward(request, response);
			return;
		}
		else if(ctrl.compareTo(GlobalConstant.cmdClaimSubmit)==0 )
		{
			//TODO
			// Update Claim Database
			String username = (String) session.getAttribute(GlobalConstant.username);			
			
			if(username != null && pid !=null)
			{
				String claimid = this.addClaimRequest(username, pid);					
				if(claimid!=null)
				{
					session.removeAttribute(GlobalConstant.requestFormData);	
					session.setAttribute(GlobalConstant.requestLastCommand,GlobalConstant.cmdClaimSubmit);
					request.setAttribute(GlobalConstant.pid,pid);
					
					System.out.println("[CLAIM] Forward to "+GlobalConstant.JSPClaimSubmit);
					RequestDispatcher rd = request.getRequestDispatcher(GlobalConstant.JSPClaimSubmit);
					rd.forward(request, response);
					return;
				}
			}
		}		
		session.removeAttribute(GlobalConstant.requestFormData);					
		session.setAttribute(GlobalConstant.responseType,GlobalConstant.typeError);
		session.setAttribute(GlobalConstant.responseControl,GlobalConstant.cmdClaim);
		session.setAttribute(GlobalConstant.responseMsg, "Error on CLAIM Servlet!");
		session.setAttribute(GlobalConstant.requestLastCommand,GlobalConstant.cmdClaim);			
		System.out.println("[CLAIM] Forward to "+GlobalConstant.JSPError);
		RequestDispatcher rd = request.getRequestDispatcher(GlobalConstant.JSPError);
		rd.forward(request, response);
	}
	
	private String addClaimRequest(String username, String pid)
	{
		String result = null;
		
		DBClaim dbclaim = new DBClaim();
		dbclaim.setConfFile(ServletContext + GlobalConstant.configFilePath);
		
		try {
			result = dbclaim.addClaimRequest(username,pid);
		} 
		catch (Exception e) {			
			e.printStackTrace();
		}				
		return result;
		
	}
}
